package com.zhanghe.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class SessionInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取当前session  true表示如果没有则创建一个
        HttpSession session = req.getSession(true);
        // 判断当前请求的session是否合法
        req.isRequestedSessionIdValid();
        // 判断当前请求是不是从URL发出的
        req.isRequestedSessionIdFromURL();
        // 判断当前请求是不是从cookie发出的
        req.isRequestedSessionIdFromCookie();
        // 使session无效
//        session.invalidate();
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type","text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<br>");
        out.println("New Session: "+session.isNew());
        out.println("<br>");
        out.println("Session ID: "+session.getId());
        out.println("<br>");
        out.println("Session Creation Time: "+new Date(session.getCreationTime()));
        out.println("<br>");
        out.println("Request Info");
        out.println("<br>");
        out.println("Session ID from request: "+req.getRequestedSessionId());
        out.println("<br>");
        out.println("Session ID from cokkie: "+req.isRequestedSessionIdFromCookie());
        out.println("<br>");
        out.println("Session ID from URL: "+req.isRequestedSessionIdFromURL());
        out.println("<br>");
        out.println("Vaild Session ID: "+req.isRequestedSessionIdValid());
        out.println("<br>");
        Integer accessCount = (Integer) session.getAttribute("accessCount");
        if(accessCount == null)
            accessCount = 0;
        accessCount++;
        out.println("访问次数"+accessCount);
        session.setAttribute("accessCount",accessCount);
        // session过期时间 在web.xml中设置
        //<session-config>
        // <session-timeout>30</session-timeout>
        // <session-config>
        out.println("<a href="+resp.encodeURL("SessionInfo")+">");
//        resp.encodeRedirectURL("")
        out.println("refresh</a>");
        out.println("</body></html>");
    }
}
